package com.ws.weatherapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.Toast
import com.birjuvachhani.locus.*
import com.ws.weatherapp.databinding.ActivityMainBinding
import di.startDI
import models.WeatherModel
import network.Methods
import org.koin.android.ext.android.inject
import org.koin.core.context.stopKoin
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
import java.text.SimpleDateFormat
import kotlin.random.Random


class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding
    lateinit var data: WeatherModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        startDI(this)
        changeBackground()
        binding.actualWeatherLayout.setPadding(0, Random.nextInt(0,2000),0,Random.nextInt(0,2000))
        Locus.getCurrentLocation(this) { result ->
            result.location?.let {
                val service: Methods by inject()
                service.getWeather(it.latitude,it.longitude).enqueue(object:
                    Callback<WeatherModel> {
                    override fun onResponse(
                        call: Call<WeatherModel>,
                        response: Response<WeatherModel>
                    ) {
                        if (response.isSuccessful) {
                            data = response.body()!!
                            updateDesign(data.sys.sunrise,data.sys.sunset,data.dt,data.weather[0].main)
                            binding.cityTv.text = data.name
                            binding.countryTv.text = data.sys.country
                            binding.tempTv.text = data.main.temp.toInt().toString()
                        } else {
                            showToast("Ошибка, код: ${response.code()}")
                        }
                    }

                    override fun onFailure(call: Call<WeatherModel>, t: Throwable) {
                        showToast("Проверьте подклчение к интернету!")
                    }
                })

            }
            result.error?.let {
                when {
                    it.isDenied -> { showToast("Приложение не будет работать без этого разрешения!") }
                    it.isPermanentlyDenied -> { showToast("Приложение не будет работать без этого разрешения!") }
                    it.isFatal -> { showToast("Что-то сломалось :(") }
                    it.isSettingsDenied -> { showToast("Приложение не будет работать без этого разрешения!") }
                    it.isSettingsResolutionFailed -> { showToast("Не удалось получить доступ к геолокации!") }
                }
            }
        }

    }

    private fun changeBackground(){
        val currentTime= Calendar.getInstance().time.hours
        if((currentTime<5) or (currentTime>17)){
            binding.root.background = getDrawable(R.drawable.night_gradient)
        }
        else{
            binding.root.background = getDrawable(R.drawable.afternoon_gradient)
        }
    }

    private fun updateDesign(sunrise_time: Int,sunset_time: Int,server_time: Int, main_weather: String){
        when(main_weather){
            "Clear" -> {
                binding.sun.visibility = VISIBLE
                binding.iconIv.setImageResource(R.drawable.ic_ic_weather_sunny)
            }
            "Thunderstorm" -> binding.iconIv.setImageResource(R.drawable.ic_ic_weather_wind_storm)
            "Drizzle" -> binding.iconIv.setImageResource(R.drawable.ic_ic_weather_drop)
            "Clouds" -> binding.iconIv.setImageResource(R.drawable.ic_ic_weather_cloudy)
            "Snow" -> binding.iconIv.setImageResource(R.drawable.ic_ic_weather_snow)
            else -> binding.sun.visibility = GONE
        }
        val formatter = SimpleDateFormat("HH:mm")
        val timeString: String = formatter.format(Date(server_time * 1000L))
        binding.timeTv.text = timeString
        if((kotlin.math.abs(server_time - sunrise_time) <1800) or (kotlin.math.abs(server_time - sunset_time) <1800)){
            binding.root.background = getDrawable(R.drawable.morning_gradient)
        }

    }

    private fun showToast(message: String){
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show()
    }

    override fun onStop() {
        super.onStop()
        stopKoin()

    }



}